import http from '@ohos.net.http'
import { Auth } from './Auth'
import promptAction from '@ohos.promptAction'
import router from '@ohos.router'

const BASE_URL = 'http://localhost:8080'

const req = http.createHttp()

const request = <T = unknown>(
  url: string,
  method: http.RequestMethod = http.RequestMethod.GET,
  params: object = {}
) => {
  let fullUrl = BASE_URL + url
  const options: http.HttpRequestOptions = {
    header: {
      'Content-Type': 'application/json',
    },
    readTimeout: 30000,
    method,
  }

  // 如果是对象数据拼接URL，如果是其他则携带在 extraData
  if (method === http.RequestMethod.GET) {
    const urlParams = Object.keys(params).map(key => `${key}=${params[key]}`)
    fullUrl += `?${urlParams.join('&')}`
  } else {
    options.extraData = params
  }

  // 携带 token
  const user = Auth.getUser()
  if (user.token) {
    options.header['token'] = `${user.token}`
  }
  return req.request(fullUrl, options).then((res)=>{
    if (res.result) {

      // 1. 处理响应
      const response = JSON.parse(res.result as string) as {
        code: number
        message: string
        data: T
      }
      return response;
      console.log(response.message)
      if (response.code === 10000) {
        return response
      }
      // 2. 处理 token 失效
      if (response.code === 401) {
        Auth.delUser()
        router.pushUrl({
          url: 'pages/Login'
        }, router.RouterMode.Single)
      }
    }
    return Promise.reject(res.result)
  })

    .catch(err => {
      console.log(err)
      promptAction.showToast({ message: '网络错误' })
      return Promise.reject(err)
    })
    .finally(() => {
      // 销毁请求释放资源
      req.destroy()
    })



}

export class Request {
  static get<T>(url: string, params?: object) {
    return request<T>(url, http.RequestMethod.GET, params)
  }

  static post<T>(url: string, params?: object) {

    return request<T>(url, http.RequestMethod.POST, params)
  }

  static put<T>(url: string, params?: object) {
    return request<T>(url, http.RequestMethod.PUT, params)
  }

  static delete<T>(url: string, params?: object) {
    return request<T>(url, http.RequestMethod.DELETE, params)
  }
}